/***************************************************
File:           LPK_VelocityTowardsGameObject
Authors:        Christopher Onorati
Last Updated:   5/17/2019
Last Version:   2018.3.14

Description:
  This component can be added to any object with a
  RigidBody to cause it to apply a velocity force towards
  another object.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_VelocityTowardsGameObject
* DESCRIPTION : This component can be added to any game object with a RigidBody to cause it to move towards a game object.
**/
[RequireComponent(typeof(Transform), typeof(Rigidbody2D))]
public class LPK_VelocityTowardsGameObject : LPK_Component
{
    /************************************************************************************/

    public bool m_bOnlyOnce = false;

    [Tooltip("Game object to move towards.  If set to null, try to find the first object with the specified tag.")]
    [Rename("Target Game Object")]
    public Transform m_pTargetGameObject;

    [Tooltip("Tags to move the object towards.  This will start at the top trying to find the first object of the tag.")]
    [TagDropdown]
    public string[] m_TargetTags;

    public float m_flRadius = 10.0f;

    public float m_flSpeed = 5;

    /************************************************************************************/

    bool m_bHasAppliedVelocity;

    /************************************************************************************/
    
    Transform   m_cTransform;
    Rigidbody2D m_cRigidBody;

    /**
    * FUNCTION NAME: OnStart
    * DESCRIPTION  : Sets rigidbody component.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override protected void OnStart()
    {
        m_cTransform = GetComponent<Transform>();
        m_cRigidBody = GetComponent<Rigidbody2D>();
    }

    /**
    * FUNCTION NAME: Update
    * DESCRIPTION  : Applies ongoing velocity if appropriate.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void Update()
    {
        ApplyVelocity();
    }

    /**
     * FUNCTION NAME: ApplyVelocity
     * DESCRIPTION  : Applies velocity to object.
     * INPUTS       : None
     * OUTPUTS      : None
     **/
    void ApplyVelocity()
    {
        if (m_bOnlyOnce && m_bHasAppliedVelocity)
            return;

        if (m_pTargetGameObject == null)
            if (!FindGameObject())
                return;

        //Velocity application.
        m_cRigidBody.velocity = (m_pTargetGameObject.position - m_cTransform.position).normalized * m_flSpeed;

        m_bHasAppliedVelocity = true;
    }

    /**
     * FUNCTION NAME: FindGameObject
     * DESCRIPTION  : Applies ongoing velocity if appropriate.
     * INPUTS       : None
     * OUTPUTS      : bool - True/false of if a game object was found and set.
     **/
    bool FindGameObject()
    {
        for (int i = 0; i < m_TargetTags.Length; i++)
        {
            List<GameObject> objects = new List<GameObject>();
            GetGameObjectsInRadius(objects, m_flRadius, 1, m_TargetTags[i]);

            if(objects[0] != null)
            {
                m_pTargetGameObject = objects[0].transform;
                return true;
            }
        }

        return false;
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_VelocityTowardsGameObject))]
public class LPK_VelocityTowardsGameObjectEditor : Editor
{
    SerializedProperty targetObject;
    SerializedProperty targetTags;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        targetObject = serializedObject.FindProperty("m_pTargetGameObject");
        targetTags = serializedObject.FindProperty("m_TargetTags");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_VelocityTowardsGameObject owner = (LPK_VelocityTowardsGameObject)target;

        LPK_VelocityTowardsGameObject editorOwner = owner.GetComponent<LPK_VelocityTowardsGameObject>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_VelocityTowardsGameObject)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_VelocityTowardsGameObject), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_VelocityTowardsGameObject");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        owner.m_bOnlyOnce = EditorGUILayout.Toggle(new GUIContent("Only Once", "Whether the velocity should ba applied every frame. Will only be applied once otherwise."), owner.m_bOnlyOnce);
        EditorGUILayout.PropertyField(targetObject, true);
        LPK_EditorArrayDraw.DrawArray(targetTags, LPK_EditorArrayDraw.LPK_EditorArrayDrawMode.DRAW_MODE_BUTTONS);
        owner.m_flRadius = EditorGUILayout.FloatField(new GUIContent("Detect Radius", "Max distance used to search for game objects.  If set to 0, detect objects anywhere."), owner.m_flRadius);
        owner.m_flSpeed = EditorGUILayout.FloatField(new GUIContent("Force", "Force to be applied."), owner.m_flSpeed);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
